package com.jiangnanxiaoguan.interceptor;

import com.jiangnanxiaoguan.common.Result;
import com.jiangnanxiaoguan.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author 不愿透露姓名的狂热者
 * @version 1.0
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> duplicateKeyExceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String errorMessage = ex.getMessage();
        log.error(errorMessage);
        if (errorMessage.contains("Duplicate entry")) {
            String duplicateKey = errorMessage.split(" ")[2] + "已存在！";
            duplicateKey = duplicateKey.replace("'", "");
            return Result.error(duplicateKey);
        }
        return Result.error("发生了未知错误");
    }

    @ExceptionHandler(BusinessException.class)
    public Result businessExceptionHandler(BusinessException ex) {
        String message = ex.getMessage();
        log.error(message);
        return Result.error(message);
    }
}
